package com.dd.keel.core.framework.protocol;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.msgpack.MessagePack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.alibaba.fastjson.JSON;
import com.dd.keel.core.framework.model.RequestModel;
import com.dd.keel.core.framework.model.ResponseModel;
import com.dd.keel.core.framework.server.ServerLogicHandler;
import com.dd.keel.core.framework.service.ServiceInvoke;

/**
 * handle logic Replace MsgPack with standard JSON format, because different
 * language api of MsgPack are not compatible
 * 
 * @author Kevin.XU
 *
 */
public class SoaServerLogicHandler implements ServerLogicHandler {

	final static private Logger LOGGER = LoggerFactory
			.getLogger(SoaServerLogicHandler.class);

	@Override
	public Object handle(Object requestObj) throws Exception {
		SoaMsg request = (SoaMsg) requestObj;
		// decode body
		Map<String, Object> requestMap = (Map<String, Object>) JSON.parse(new String(request.getBody(), "UTF-8"));
		String group = (String) requestMap.get("group");
		String service = (String) requestMap.get("service");
		String version = (String) requestMap.get("version");
		String trace_id = (String) requestMap.get("trace_id");
		String trace_span_id = (String) requestMap.get("trace_span_id");
		Map<String, Object> bodyMap = (Map<String, Object>) requestMap
				.get("data");
		Map<String, Object> responseMap = ServiceInvoke.invokeLocalSoaService(
				group, service, version, trace_id, trace_span_id, bodyMap);
		if (responseMap == null) {
			LOGGER.error("invoke service failed : not found service : " + group
					+ ',' + service + ',' + version);
			throw new Exception("not found service " + service + ":" + version);
		}
		String raw = JSON.toJSONString(responseMap);
		SoaMsg response = new SoaMsg();
		response.setBody(raw.getBytes("UTF-8"));
		response.setIdentifier(request.getIdentifier());
		response.setType(SoaMsg.getResponseType(request.getType()));
		return response;
	}
}
